<?php
require_once (HOME . '/include/base/BackendController.php');
class connector extends BackendController {
	/**
	 *
	 * @var m_data
	 */
	private $mod_data = NULL;
	
	/**
	 * elfinder connector 配置
	 *
	 * @var array
	 */
	private $opts;
	function __construct() {
		// parent::__construct();
		$this->connector ();
	}
	function connector() {
		$this->mod_data = spClass ( 'm_data' );
		
		$this->opts = array (
				'bind' => array (
						// '*' => 'logger',
						'*' => array (
								$this,
								'transmit' 
						) 
				),
				'roots' => array ( // TODO 不充许上传的文件禁止上传
						array (
								'driver' => 'LocalFileSystem', // driver for accessing
								                               // file system (REQUIRED)
								'path' => HOME . '/data/files/', // path to files
								                                 // (REQUIRED)
								'URL' => 'http://10.202.1.109/workForYangtzeu/data/files/' 
						// URL
						// to
						// files
						// (REQUIRED)
						// 'accessControl'
						// =>
						// 'access'
						// //
						// disable
						// and
						// hide
						// dot
						// starting
						// files
						// (OPTIONAL)
						
						 )
				),
				'db' =>array(
							'db_class' => spClass('m_data')
						) 
		);
	}
	function index() {
		include_once HOME . '/include/library/elFinder/elFinderConnector.class.php';
		include_once HOME . '/include/library/elFinder/elFinder.class.php';
		include_once HOME . '/include/library/elFinder/elFinderVolumeDriver.class.php';
		include_once HOME . '/include/library/elFinder/elFinderVolume/elFinderVolumeLocalFileSystem.class.php';
		include_once HOME . '/include/library/elFinder/elFinderVolume/elFinderVolumeMySQL.class.php';
		include_once HOME . '/include/library/elFinder/elFinderVolume/elFinderVolumeFTP.class.php';
		
		// $opts = require HOME . '/configs/elFinderConfig.php';
		// var_dump($opts);
		// sleep(3);///
		// $opts = array (
		// 'roots' => array (
		// array (
		// 'driver' => 'LocalFileSystem', // driver for accessing
		// // file system (REQUIRED)
		// 'path' => 'G:\Zend
		// Debug\workForYangtzeu\administrator\..\\data/files/', // path to
		// files (REQUIRED)
		// 'URL' => 'G:\Zend
		// Debug\workForYangtzeu\administrator\..\\data/files/', // URL
		// // to
		// // files
		// // (REQUIRED)
		// 'accessControl' => 'access' // disable and hide dot starting files
		// // (OPTIONAL)
		
		// )
		// )
		// );
		
		header ( 'Access-Control-Allow-Origin: *' );
		$connector = new elFinderConnector ( new elFinder ( $this->opts ), true );
		$connector->run ();
	}
	public function transmit($cmd, $result, $args, $elfinder) {
		// dump(func_get_args());
		if (array_key_exists ( 'error', $result )) {
			$this->_handle_error ( $result, $args );
		} else { // 错误处理完毕
			
			switch ($cmd) {
				case 'open' :
					$this->_cmd_open ( $result, $args, $elfinder );
					break;
				case 'mkdir' :
					$this->_cmd_mkdir( $result,$args,$elfinder);
					break;
				case 'upload' :
					$this->_cmd_upload ( $result, $args, $elfinder );
					break;
				case 'rm' :
					$this->_cmd_remove( $result, $args, $elfinder);
					break;
				default :
					break;
			}
		}
	}
	/**
	 * 处理来自elfinder 的错误
	 *
	 * @param array $result        	
	 * @param array $args        	
	 */
	private function _handle_error($result, $args) {
		dump ( func_get_args () );
		// TODO 错误处理
		// 解析相应的错误
		// TODO 做一些清扫工作
		// 清扫那些额外的数据
		// TODO做一些错误的判断
		// TODO 最后记录
	}
	private function _cmd_open($result, $args, $elfinder) {
		// dump(func_get_args());
		// json_encode($result);
		// 记录下
		//
	}
	private function _cmd_mkdir($result,$args,$elfinder){
// 		dump($result);
// 		dump($args);
		$mod_pcategory = spClass('m_pcategory');
		if(!empty($result['added'])){
			$mod_pcategory->create(array('content'=>$args['content'],'path'=>base64_decode ( substr ( $result['added'][0] ['hash'], 3, strlen( $result['added'][0] ['hash'] ) ) )));
		}
// 		$mod_pcategory->		
	}
	private function _cmd_remove($result, $args, $elfinder){
		dump($result);
				$mod_data = spClass('m_data');
		if (array_key_exists ( 'removed', $result )) {
			foreach ( $result ['removed'] as $removed_file ) {
				if(!empty($result['removed'])  ){
					$mod_data->delete(array());
				}
				
// 				$hash = $elfinder->decode($removed_file['hash']);
// 				dump($hash);
			}
		}
// 		{"removed":["l1_MTIxMlxzZGZkc2Y"]}
	}
	private function _cmd_upload($result, $args, $elfinder) {
		// dump ( func_get_args () );
		// TODO成功后应该把数据加入到指定的数据库
		
		// 数据模型有关
		// $this->mod_data->find();
		// dump ( $result );
		if (array_key_exists ( 'added', $result )) {
			foreach ( $result ['added'] as $added_file ) {
				// TODO 将文件写入到数据库
				// dump($added_file);
				$row ['mime'] = $added_file ['mime'];
				$row ['name'] = $added_file ['name'];
				$row ['size'] = $added_file ['size'];
				$row ['add_time'] = date ( 'Y-m-d H:i:s', $added_file ['ts'] );
				$row ['path'] = base64_decode ( substr ( $added_file ['hash'], 3, strlen( $added_file ['hash'] ) ) );
				
				// dump($added_file);
				// start give birth_time
				if (function_exists ( 'exif_read_data' ) && substr($added_file ['mime'], 0,5) == 'image') {
					$filename = $elfinder->realpath ( $added_file ['hash'] );
					$exif = exif_read_data ( $filename, 'FILE' );
					// give birth_time
					$array_keys = array (
							'DateTimeOriginal',
							'DateTimeDigitized',
							'DateTime',
							'FileDateTime' 
					);
					foreach ( $array_keys as $key ) {
						if (array_key_exists ( $key, $exif )) {
							$row ['birth_time'] = date_sql ( $exif [$key] );
							break;
						}
					}
					// if (array_key_exists ( 'DateTimeOriginal', $exif )) {
					// $row ['birth_time'] = $exif ['DateTimeOriginal'];
					// } else if (array_key_exists ( 'DateTimeDigitized', $exif
					// )) {
					// $row ['birth_time'] = $exif ['DateTimeDigitized'];
					// } else if (array_key_exists ( 'DateTime', $exif )) {
					// $row ['birth_time'] = $exif ['DateTime'];
					// } else if (array_key_exists ( 'FileDateTime', $exif )) {
					// $row ['birth_time'] = date ( 'Y-m-d H:i:s', $exif
					// ['FileDateTime'] );
					// }
					// dump($exif);
					// dump($row);
				} else {
					$row ['birth_time'] = date ( 'Y-m-d H:i:s', filectime ( $filename ) );
				} // end of give birth_time
				
				$row ['album'] = array (
						'parent_id' => 0,
						'name' => 'THIS IS A TEST !!!',
						'birth_id' => date ( 'Y-m-d H:i:s', time () ) 
				);
// 				dump ( $row );
				$this->mod_data->el_create_file ( $row, TRUE );
				// 更新其他信息
				// TODO 更新相关权限
				
				// TODO 更新相册
			} // end of foreach
		}
	}
	/**
	 * 创建一个相册
	 */
	public function createAlbum() {
		$mod_pcategory = spClass ( 'm_pcategory' );
	}
	
	/**
	 *
	 * @param path $el_file
	 *        	文件的路径
	 * @param path $target
	 *        	相册的路径
	 */
	private function _photo_into_album($el_file, $target) {
		// TODO update the album and associate the album and file
	}
}
$str = implode ( '', file ( 'log' ) ) + 1;
fwrite ( fopen ( 'log', 'w+' ), $str );

// function logger($cmd, $result, $args, $elfinder) {
// 	var_dump(func_get_args());
// }
